package com.jinxin.platform.cdelecinspect.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {
    /**
     *二维码实现
     * @param msg
     *
     */
    public static String getBarCode(String msg){
        String path = "";
        try {
            path = "D:\\QRCode" + "/" + msg + ".jpg";
            File file=new File(path);
            OutputStream ous=new FileOutputStream(file);
            if(StringUtils.isEmpty(msg) || ous==null)
                return null;
            String format = "jpg";
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType,String> map =new HashMap<>();
            //设置编码 EncodeHintType类中可以设置MAX_SIZE， ERROR_CORRECTION，CHARACTER_SET，DATA_MATRIX_SHAPE，AZTEC_LAYERS等参数
            map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
            map.put(EncodeHintType.MARGIN,"2");
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE,200,200,map);
            System.out.println("bitMatrix" + bitMatrix.toString());
            MatrixToImageWriter.writeToStream(bitMatrix,format,ous);
            return path;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
    public static void main(String[] args) {
        String msg = "gjkkkhkhk";
        //String path = "E:\\QRCode/pillar666.png";
        QRCodeUtil.getBarCode(msg);
    }

}
